var memberDAL = require('../DAL/memberDAL');
var categoryDAL = require('../DAL/categoryDAL');
var cartDAL = require('../DAL/cartDAL');
var cityDAL = require('../DAL/cityDAL');
var orderDAL = require('../DAL/orderDAL');
var addressDAL = require('../DAL/addressDAL');
var collectDAL = require('../DAL/collectDAL');
var AddressInfo = require('../Model/AddressInfo');
var OrderInfo = require('../Model/OrderInfo');
var async = require('async');

function memberController(app) {
	// body...
	/* GET home page. */
	//app.get方法第一个参数是我们添加网站可以请求的地址
	app.get('/member', function(req, res, next) {
		//个人首页
		//验证登录
		if(!req.session.customer) {
			res.redirect('/login');
		}
		var userInfo = req.session.customer;
		var redirect_url = null;

		//应用async模块的api:parallel处理并行无关联操作
		async.parallel({ //控制流程1:多级菜单加载
			categorylist: function(done) {
				//处理逻辑
				categoryDAL.getCategoryAll(function(catelist) {
					//循环构造数组对象模型
					var categorylist = create_objectArrayList(catelist, 0);

					done(null, categorylist);
				});

			}, //控制流程2：收藏信息
			newlyCollect: function(done) {
				collectDAL.getNewlyCollect(userInfo.customer_Id, 5, function(collectlist) {
					done(null, collectlist);
				});
			}, //控制流程3：最近订单前五项
			newlyOrderlist: function(done) {
				orderDAL.getNearlyOrderByCustomerId(userInfo.customer_Id, 5, function(orderlist) {
					//对订单列表进行格式化
					var list = create_orderlist(orderlist);
					done(null, list);
				});
			}, //控制流程4：未付款订单数量
			noPayOrderCounts: function(done) {
				orderDAL.noPayOrderlistByCustomerId(userInfo.customer_Id, function(count) {
					done(null, count);
				});
			}, //控制流程5：未收货的订单数量
			noReciveOrderCounts: function(done) {
				orderDAL.noReceiveOrderlistByCustomerId(userInfo.customer_Id, function(count) {
					done(null, count);
				});
			}
		}, function(err, results) {

			if(redirect_url) {
				res.redirect(redirect_url);
				req.session.redirecturl = null;
			}

			res.render('member/member', {
				categorylist: results.categorylist,
				newlyCollectlist: results.newlyCollect,
				newlyOrderlist: results.newlyOrderlist,
				noPayOrderCounts: results.noPayOrderCounts,
				noReciveOrderCounts: results.noReciveOrderCounts,
				userInfo: userInfo
			});

		});

	});

	//登录页面
	app.get('/login', function(req, res) {
		//res.render方法的第一个参数是我们请求地址对应的网页文件名
		res.render('login');
	});

	//登录验证方法
	app.post('/validatelogin', function(req, res) {
		var loginname = req.body.username.trim(); //用户名
		var loginpass = req.body.password.trim(); //密码

		//console.log('u:'+loginname+',p:'+loginpass);

		if(loginname == "" || loginpass == "") {
			return false;
			res.redirect('/login');
		}

		//验证登录
		memberDAL.validateLogin(loginname, loginpass, function(message, userInfo, status) {
			//      	
			if(status) {
				//登录成功
				req.session.customer = userInfo;
				res.send(message);
				//console.log(message);
				//res.redirect('/member');
			} else {
				//登录失败
				//res.redirect('/login');
				res.send(message);
			}

		});
	});

	//登陆退出
	app.get('/logout', function(req, res) {
		req.session.customer = null;
		res.redirect('/login');
	});

	//购物车页面
	app.get('/cart', function(req, res) {

		//用户必须先登录才能从数据库读取购物车记录并进行加载
		//验证登录
		var userInfo = req.session.customer;
		if(!userInfo) {
			res.redirect('/login');
		}

		//应用async模块的api:parallel处理并行无关联操作
		async.parallel({ //控制流程1:多级菜单加载
			categorylist: function(done) {
				//处理逻辑
				categoryDAL.getCategoryAll(function(catelist) {
					//循环构造数组对象模型
					var categorylist = create_objectArrayList(catelist, 0);

					done(null, categorylist);
				});
			}, //控制流程2：加载购物车数据
			cartlist: function(done) {
				//购物车数据
				cartDAL.getAllCartData(userInfo.customer_Id, function(datalist) {
					// body...
					//console.log(datalist);
					done(null, datalist);
				});
			}
		}, function(err, results) {

			res.render('cart', {
				categorylist: results.categorylist,
				cartlist: results.cartlist,
				userInfo: userInfo
			});
		});

	});

	//订单提交成功页面
	app.get('/order/order_success', function(req, res) {
		//验证登录
		var userInfo = req.session.customer;
		if(!userInfo) {
			res.redirect('/login');
		}

		//应用async模块的api:parallel处理并行无关联操作
		async.parallel({ //控制流程1:多级菜单加载
			categorylist: function(done) {
				//处理逻辑
				categoryDAL.getCategoryAll(function(catelist) {
					//循环构造数组对象模型
					var categorylist = create_objectArrayList(catelist, 0);

					done(null, categorylist);
				});
			}, //控制流程2：加载新订单信息，并将id作为传递参数
			neworder: function(done) {
				orderDAL.getNewOrderByCustomerId(userInfo.customer_Id, function(result) {
					done(null, result[0]);
				});
			}
		}, function(err, results) {

			res.render('order/order_success', {
				categorylist: results.categorylist,
				neworder: results.neworder,
				userInfo: userInfo
			});
		});

	});

	//订单提交处理函数
	app.post('/order/confirmorderhandle', function(req, res) {
		//console.log('请求');
		//验证登录
		var userInfo = req.session.customer;
		if(!userInfo) {
			res.status(200).send({
				url: '/login',
				message: '未登录'
			});
		} else {
			var pdIdList = req.body.cartPdlist; //购买产品的ID列表
			var pdNumList = req.body.cartPdNum; //购买产品的数量列表
			var address_Id = req.body.address_Id; //购买用户收货地址ID
			var customer_Id = userInfo.customer_Id; //购买用户ID
			var message = req.body.message; //买家留言
			var express_fee = req.body.express_fee; //快递费
			var totalprice = req.body.totalprice; //订单总额
			var check_invoices = req.body.check_invoices; //是否开具发票
			var pay_type = req.body.pay_type; //支付方式

			console.log(pdIdList);

			var orderInfo = new OrderInfo();
			orderInfo.setpdIdList(pdIdList);
			orderInfo.setpdNumList(pdNumList);
			orderInfo.setaddress_Id(address_Id);
			orderInfo.setcustomer_Id(customer_Id);
			orderInfo.setmessage(message);
			orderInfo.setexpress_fee(express_fee);
			orderInfo.settotalprice(totalprice);
			orderInfo.setcheck_invoices(check_invoices);
			orderInfo.setpay_type(pay_type);

			orderDAL.createOrder(orderInfo, function(result) {
				//console.log(orderid);

				res.status(200).send({
					url: '/order/order_success',
					message: '订单提交成功'
				});
			});

		}
	});

	//订单确认页面
	app.get('/order/order_confirm', function(req, res) {

		//验证登录
		var userInfo = req.session.customer;
		if(!userInfo) {
			res.redirect('/login');
		}

		//应用async模块的api:parallel处理并行无关联操作
		async.parallel({ //控制流程1:多级菜单加载
			categorylist: function(done) {
				//处理逻辑
				categoryDAL.getCategoryAll(function(catelist) {
					//循环构造数组对象模型
					var categorylist = create_objectArrayList(catelist, 0);

					done(null, categorylist);
				});

			}, //流程2:收货地址列表数据
			addresslist: function(done) {
				//数据加载
				addressDAL.getAddressByCustomerId(userInfo.customer_Id, function(addresslist) {
					done(null, addresslist);
				})
			}, //流程3:加载提交选中的商品数据信息
			productlist: function(done) {
				var productlist = req.session.cartPdlist;
				done(null, productlist);
			}
		}, function(err, results) {
			var checkIdList = req.session.checkIdList;
			var cartPdNum = req.session.cartPdNum;
			//快递费取几个商品中最高的
			var val = 0;
			var list = results.productlist;
			for(i = 0; i < list.length; i++) {
				var fee = parseFloat(list[i].product_expressfee);
				if(fee > parseFloat(val)) {
					val = list[i].product_expressfee;
				}
			}

			//console.log('快递费：'+val);
			//console.log(cartPdNum);
			res.render('order/order_confirm', {
				categorylist: results.categorylist,
				addresslist: results.addresslist,
				productlist: results.productlist,
				order_expressfee: val,
				checkIdList: checkIdList,
				cartPdNum: cartPdNum,
				userInfo: userInfo
			});

		});

	});

	//提交订单信息到确认订单页面
	app.post('/order/confirm_ready', function(req, res) {
		//验证登录
		var userInfo = req.session.customer;
		if(!userInfo) {
			res.redirect('/login');
		}

		//在这里将提交的准备购买的商品信息取出来,放到session中
		//获取勾选的id数组
		var checkIdList = req.body.check_productid;
		var productNum = req.body.check_pd_num;
		req.session.cartPdlist = '';
		req.session.checkIdList = '';
		req.session.cartPdNum = '';

		//加载选中的产品数据信息
		orderDAL.getConfirmorder(userInfo.customer_Id, checkIdList, function(results) {
			req.session.cartPdlist = results;
			req.session.checkIdList = checkIdList;
			req.session.cartPdNum = productNum;

			res.redirect('/order/order_confirm');
		});

	});

	//测试
	app.get('/test', function(req, res) {
		var time = new Date().getTime();
		res.send(time);
	});

	//注册页面
	app.get('/register', function(req, res) {
		//res.render方法的第一个参数是我们请求地址对应的网页文件名
		//var code=req.session.CAPTCHA_KEY;
		//console.log('code:'+code);
		res.render('register');
	});

	//注册方法
	app.post('/regMember', function(req, res) {
		var loginname = req.body.username; //用户名
		var loginpass = req.body.password; //密码
		var loginrepass = req.body.repassword; //重复密码
		var mobile_phone = req.body.mobile_phone; //手机号
		var validatecode = req.body.valcode.toUpperCase(); //验证码
		//获取验证码
		var code = req.session.CAPTCHA_KEY;
		//业务逻辑
		if(loginname.trim() == "" || loginpass.trim() == "" || loginrepass.trim() == "" || mobile_phone.trim() == "" || validatecode.trim() == "") {
			return false;
			res.redirect('/register');
		}
		if(loginrepass != loginpass) {
			return false;
			res.redirect('/register');
		}

		//console.log(validatecode);
		//console.log('code:'+code);

		if(validatecode == code) {
			//验证码通过进行用户注册        	
			memberDAL.regMember(loginname, loginpass, mobile_phone, function(message, result) {
				console.log(message);
				res.redirect('/login');
			});
		} else {
			return false;
			res.redirect('/register');
		}
	});

	//个人订单
	app.get('/member/member_orderlist', function(req, res, next) {

		//验证登录
		if(!req.session.customer) {
			res.redirect('/login');
		}
		var userInfo = req.session.customer;

		//应用async模块的api:parallel处理并行无关联操作
		async.parallel({ //控制流程1:多级菜单加载
			categorylist: function(done) {
				//处理逻辑
				categoryDAL.getCategoryAll(function(catelist) {
					//循环构造数组对象模型
					var categorylist = create_objectArrayList(catelist, 0);

					done(null, categorylist);
				});

			}, //控制流程2：用户信息
			userInfo: function(done) {
				var userInfo = req.session.customer;
				done(null, userInfo);
			}, //控制流程3：用户订单信息
			orderlist: function(done) {
				orderDAL.getOrderByCustomerId(userInfo.customer_Id, function(orderlist) {
					//对订单列表进行格式化
					var list = create_orderlist(orderlist);
					done(null, list);
				});
			}
		}, function(err, results) {

			res.render('member/member_orderlist', {
				categorylist: results.categorylist,
				orderlist: results.orderlist,
				userInfo: results.userInfo
			});

		});

	});

	//订单列表格式转换函数
	//当有数据的orderid相同时,将orderid相同的数据归为一组加入一个list
	function create_orderlist(data) {
		var list = [];
		//将第一条数据的订单id赋值给临时变量，为后续比对做准备			

		for(i = 0; i < data.length; i++) {
			//记录当前循环的订单ID
			var order_id = data[i].order_Id;
			var obj = new Object();
			obj.order_Id = order_id; //订单ID
			obj.order_code = data[i].order_code; //订单编号
			obj.order_status = data[i].order_status; //订单状态
			obj.pay_type = data[i].pay_type; //订单支付方式
			obj.customer_name = data[i].customer_name; //收货人姓名
			obj.formateorder_time = data[i].formateorder_time; //收货时间
			obj.address_details = data[i].address_details; //收货详细地址
			var orderamount; //每笔订单总金额
			//新建商品列表
			var pdlist = [];
			var pdobj = new Object();
			pdobj.product_Id = data[i].product_Id; //商品id
			pdobj.product_name = data[i].product_name; //商品名称
			pdobj.product_img = data[i].product_img; //商品展示图
			pdobj.num = data[i].num; //商品购买数量
			//商品小计价格 //计算小计  = 数量 * （单价 - 优惠价）
			var xiaoji = ((parseFloat(data[i].new_price) - parseFloat(data[i].product_favourable)) * parseInt(data[i].num)).toFixed(2);
			console.log('xiaoji:' + xiaoji);
			pdobj.totalprice = xiaoji;
			//计算总价格
			orderamount = xiaoji;
			pdlist.push(pdobj);
			//在当前节点以下循环遍历
			for(j = i + 1; j < data.length; j++) {
				//从下一个开始比对
				if(order_id == data[j].order_Id) {
					i++;
					var otherpdobj = new Object();
					//如果相同，则两个数据是一组订单，则压入相同的list
					otherpdobj.product_Id = data[j].product_Id;
					otherpdobj.product_name = data[j].product_name;
					otherpdobj.product_img = data[j].product_img;
					otherpdobj.num = data[j].num;
					//商品价格小计
					var xiaoji2 = ((parseFloat(data[i].new_price) - parseFloat(data[i].product_favourable)) * parseInt(data[j].num)).toFixed(2);
					console.log('xiaoji2:' + xiaoji2);
					otherpdobj.totalprice = xiaoji2;
					orderamount = parseFloat(orderamount) + parseFloat(xiaoji2);
					pdlist.push(otherpdobj);
				}
			}
			//将总价格放入对象
			obj.orderamount = (parseFloat(orderamount) + parseFloat(data[i].product_expressfee)).toFixed(2);
			obj.pdlist = pdlist;

			//console.log('test3:'+orderamount);

			list.push(obj);
		}
		return list;
	}

	//请求城市地区数据

	//收货地址管理页面
	app.get('/member/member_address', function(req, res) {
		//验证登录
		if(!req.session.customer) {
			res.redirect('/login');
		}
		var userInfo = req.session.customer;
		//应用async模块的api:parallel处理并行无关联操作
		async.parallel({ //控制流程1:多级菜单加载
			categorylist: function(done) {
				//处理逻辑
				categoryDAL.getCategoryAll(function(catelist) {
					//循环构造数组对象模型
					var categorylist = create_objectArrayList(catelist, 0);

					done(null, categorylist);
				});

			}, //控制流程2:加载城市信息
			citylist: function(done) {
				cityDAL.getCitylistByUpid(0, function(citylist) {
					done(null, citylist);
				});
			}, //控制流程3:加载已添加收货地址列表数据
			addresslist: function(done) {
				addressDAL.getAddressByCustomerId(userInfo.customer_Id, function(addresslist) {
					done(null, addresslist);
				});
			}, //控制流程4：获取收货地址数目
			addresslistcount: function(done) {
				addressDAL.getAddressCounts(userInfo.customer_Id, function(counts) {
					done(null, counts);
				});
			}
		}, function(err, results) {

			res.render('member/member_address', {
				categorylist: results.categorylist,
				citylist: results.citylist,
				addresslist: results.addresslist,
				addresslistcount: results.addresslistcount,
				userInfo: userInfo
			});

		});

	});

	//添加收货地址信息请求方法
	app.post('/member/addresshandle', function(req, res) {
		var userInfo = req.session.customer;
		if(!userInfo) {
			res.redirect('/login');
		}
		//获取表单数据
		var maincitylist = req.body.cityText; //城市
		var areaOfCity = req.body.AreaText; // 区
		var streetOfArea = req.body.streetText; //街道
		var adrs_detail = req.body.adrs_detail; //详细地址
		var adrs_code = req.body.adrs_code; //邮编
		var customer_name = req.body.customer_name; //收货人
		var customer_code = req.body.customer_code; //身份证号
		var customer_mobile = req.body.customer_mobile; //手机号
		var customer_tel = req.body.customer_tel; //固定电话
		var is_default = 0; //设置默认

		if(req.body.is_default) { //如果未填则值为空,返回false
			is_default = req.body.is_default;
		}

		//对收货地址模型对象赋值
		var addressInfo = new AddressInfo();
		addressInfo.setaddress_city(maincitylist);
		addressInfo.setaddress_details(maincitylist + ' ' + areaOfCity + ' ' + streetOfArea + ' ' + adrs_detail);
		addressInfo.setaddress_code(adrs_code);
		addressInfo.setcustomer_name(customer_name);
		addressInfo.setcustomer_code(customer_code);
		addressInfo.setmobilephone(customer_mobile);
		addressInfo.settelphone(customer_tel);
		addressInfo.setisDefault(is_default);
		//当前登录用户ID
		addressInfo.setcustomer_Id(userInfo.customer_Id);

		addressDAL.addAddressByCustomerId(addressInfo, function(results) {
			if(results) {
				res.redirect('/member/member_address');
			} else {
				res.redirect('/member/member_address');
			}
		});

	});

	//删除收货地址方法
	app.get('/member/deleteAddressHandle/:id', function(req, res) {
		var userInfo = req.session.customer;
		if(!userInfo) {
			res.redirect('/login');
		}

		var address_Id = parseInt(req.params.id);

		addressDAL.deleteAddressByCustomerId(userInfo.customer_Id, address_Id, function(results) {
			if(results) {
				res.redirect('/member/member_address');
			} else {
				res.redirect('/member/member_address');
			}
		});
	});

	//提交修改收货地址默认设置处理方法
	app.get('/member/updateAdrsDefaulthandle/:id', function(req, res) {
		var userInfo = req.session.customer;
		if(!userInfo) {
			res.redirect('/login');
		}

		var address_Id = parseInt(req.params.id);
		var customer_Id = parseInt(userInfo.customer_Id);
		//console.log(customer_Id+' '+address_Id);
		//执行处理方法
		addressDAL.updateAddressDefault(customer_Id, address_Id, function(results) {
			if(results) {
				//修改成功
				res.redirect('/member/member_address');
			} else {
				//修改失败
				res.redirect('/member/member_address');
			}
		});

	});

	//ajax请求城市地区处理
	app.get('/member/ajaxToGetCity', function(req, res) {
		//通过参数获取id
		var up_id = parseInt(req.query.id);
		cityDAL.getCitylistByUpid(up_id, function(citylist) {
			//console.log(citylist);
			res.send(citylist);
		});
	});

	//递归构造树型数组对象
	function create_objectArrayList(data, pid) {
		pid = pid || 0;
		var list = [];
		data.map(function(item) {
			if(item.up_id == pid) {
				item.list = create_objectArrayList(data, item.category_Id);
				list.push(item);
			}
		});
		return list;
	}

	//付款页面
	app.get('/member/pay', function(req, res) {
		//验证
		var userInfo = req.session.customer;
		if(!userInfo) {
			res.redirect('/login');
		}
		var order_Id = req.query.order_id;
		//console.log('orderid:'+order_Id);

		orderDAL.getOrderByCustomerIdAndOrderId(userInfo.customer_Id, order_Id, function(result) {
			res.render('member/pay', {
				userInfo: userInfo,
				orderInfo: result[0]
			});
		});
	})

	//支付修改订单状态处理函数
	app.post('/member/payHandle', function(req, res) {
		var order_Id = req.body.order_Id;
		console.log(order_Id);

		//验证
		var userInfo = req.session.customer;
		if(!userInfo) {
			res.status(200).send({
				url: '/login',
				message: '未登录'
			});
		} else {
			orderDAL.payOrderStatusByCustomerIdAndOrderId(userInfo.customer_Id, order_Id, function(result) {
				res.status(200).send({
					url: '/member/pay_success',
					message: '支付成功'
				});
			});
		}
	});

	//支付成功页面
	app.get('/member/pay_success', function(req, res) {
		var userInfo = req.session.customer;

		res.render('member/pay_success', {
			userInfo: userInfo
		});
	});

	//个人用户修改密码页面
	app.get('/member/member_modifypass', function(req, res) {
		//验证登录
		if(!req.session.customer) {
			res.redirect('/login');
		}
		var userInfo = req.session.customer;
		var redirect_url = null;

		//应用async模块的api:parallel处理并行无关联操作
		async.parallel({ //控制流程1:多级菜单加载
			categorylist: function(done) {
				//处理逻辑
				categoryDAL.getCategoryAll(function(catelist) {
					//循环构造数组对象模型
					var categorylist = create_objectArrayList(catelist, 0);

					done(null, categorylist);
				});
			}
		}, function(err, results) {

			if(redirect_url) {
				res.redirect(redirect_url);
				req.session.redirecturl = null;
			}

			res.render('member/member_modifypass', {
				categorylist: results.categorylist,
				userInfo: userInfo
			});

		});
	});

	//个人用户密码修改方法
	app.post('/member/member_modifypasshandle', function(req, res) {
		var userInfo = req.session.customer;
		var oldpass = req.body.oldpass;
		var newpass = req.body.newpass;
		//验证登录
		if(!userInfo) {
			res.status(200).send({
				url: '/login',
				message: '未登录'
			});
		} else {

			//应用async模块的api:parallel处理并行无关联操作
			async.parallel({ //控制流程1:多级菜单加载
				categorylist: function(done) {
					//处理逻辑
					categoryDAL.getCategoryAll(function(catelist) {
						//循环构造数组对象模型
						var categorylist = create_objectArrayList(catelist, 0);

						done(null, categorylist);
					});
				}
			}, function(err, results) {

				memberDAL.modifyMemberPass(userInfo.loginname, oldpass, newpass, function(message, mpresult) {
					var link_url = "/member";
					res.status(200).send({
						url: link_url,
						message: message
					});
				});
			});
		}
	});
}

module.exports = memberController;